package com.google.code.synchronized_player;

import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;

public class MainActivity extends Activity {

	
    ListView playListView;
	PlayList playList;
	PlayListAdapter adapter;
    /** Called when the activity is first created. */
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        playList = new PlayList(this.getApplicationContext());
        playListView = (ListView)this.findViewById(R.id.playlist);
        adapter = new PlayListAdapter(this, playList.getTracksList());
        playListView.setAdapter(adapter);
        new Thread(new Server()).start();
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.main_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.settings:
            startActivity(new Intent(this.getApplicationContext(), SettingsActivity.class));
            return true;
        case R.id.add_to_play_list:
        	this.startActivityForResult(new Intent(this.getApplicationContext(), SelectorActivity.class), 1);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	String s = data.getStringExtra("path");
    	if(!s.equals("")) { 
	    	playList.addTrack(s);
	    	adapter.notifyDataSetChanged();
    	}
    }
    
    public void play_track(String path) {
        MediaPlayer mediaPlayer = new  MediaPlayer();
        try {
              mediaPlayer.setDataSource(path);
              mediaPlayer.prepare();
              mediaPlayer.start();
        } catch (IllegalArgumentException iae) {
              // TODO Auto-generated catch block
              iae.printStackTrace();
        } catch (IllegalStateException ise) {
              // TODO Auto-generated catch block
              ise.printStackTrace();
        } catch (IOException ioe) {
              // TODO Auto-generated catch block
              ioe.printStackTrace();
        } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
        }
    }
}